from re import search
from statistics import mode
from tabnanny import verbose
from tkinter import CASCADE
from unicodedata import name
from xml.etree.ElementInclude import default_loader
from django.db import models
from django.conf import settings
from django.contrib import admin
from django.contrib.auth.models import User
from django.db import models
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.utils.timezone import now
from rest_framework.authtoken.models import Token
from common import txt2pic

# Create your models here.

@receiver(post_save, sender=settings.AUTH_USER_MODEL)
def create_auth_token(sender, instance=None, created=False, **kwargs):
    if created:
        Token.objects.create(user=instance)

# 用户扩展信息
class UserExtension(models.Model):
    """ 用户拓展信息模型 """
    sex_choices = (
        ('0','男'),
        ('1','女')
    )
    user = models.OneToOneField(User,verbose_name='用户ID',help_text='用户ID（OneToOneField）', on_delete=models.CASCADE, related_name='extension')
    name = models.CharField(max_length=30, verbose_name='真实姓名', help_text='真实姓名（CharField）', blank=True)
    sex = models.CharField(max_length=1, verbose_name='性别', help_text='性别（CharField，可选值:0，1）', blank=True, choices=sex_choices, default='0')
    grade = models.ForeignKey('Grade', verbose_name='班级', help_text='班级（ForeignKey）', null=True, blank=True, on_delete=models.SET_NULL)
    role = models.ForeignKey('Role', verbose_name='岗位', help_text='岗位（ForeignKey）', null=True, blank=True, on_delete=models.SET_NULL)
    
    class Meta:
        ordering = ['-id']
        verbose_name = '用户信息'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name

@admin.register(UserExtension)
class UserExtensionAdminModel(admin.ModelAdmin):
    # 添加分页
    list_per_page = 20
    list_display = ('id','user', 'name', 'sex', 'grade','role',)
    # 搜索框
    search_fields = ('id','user', 'name','grade',)
    # 搜索框
    search_fields = ('name', 'grade__name','role__name')
    list_filter = ('sex','role',)
    # 使用到外键下拉的字段
    autocomplete_fields = ('grade', 'role')

# 选课信息
class Score(models.Model):
    """ 选课评分信息模型 """

    user = models.ForeignKey(UserExtension,verbose_name='用户ID',help_text='用户ID（OneToOneField）',null=True, blank=True, on_delete=models.SET_NULL,)
    # 一对一会更好
    course = models.ForeignKey('Course', verbose_name='课程', help_text='课程（ForeignKey）', null=True, blank=True, on_delete=models.SET_NULL)
    score = models.SmallIntegerField(verbose_name='分数', help_text='分数（CharField）', null=True, blank=True)

    class Meta:
        ordering = ['-id']
        verbose_name = '选课评分信息'
        verbose_name_plural = verbose_name

    def __str__(self):
        # 返回评分名称
        return str(self.score)

@admin.register(Score)
class ScoreAdminModel(admin.ModelAdmin):
    """
    注册课程模型到admin
    """
    list_per_page = 20
    list_display = ('id','user', 'course','score',)
    search_fields = ('user__name','course__name','score',)
    autocomplete_fields = ('user','course')

# 岗位信息
class Role(models.Model):
    """ 岗位信息模型 """

    name = models.CharField(max_length=30, verbose_name='岗位名称', help_text='岗位名称（CharField）', blank=True)

    class Meta:
        ordering = ['-id']
        verbose_name = '岗位信息'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.name

@admin.register(Role)
class RoleAdminModel(admin.ModelAdmin):
    # 添加分页
    list_per_page = 20
    list_display = ('id', 'name')
    # 搜索框
    search_fields = ('name',)

# 班级
class Grade(models.Model):
    """ 班级名称 """

    name = models.CharField(max_length=60, verbose_name='班级名称', help_text='班级名称（CharField）')
    createdBy = models.ForeignKey(UserExtension,max_length=30, verbose_name='创建人', help_text='创建人（ForeignKey）', blank=True,on_delete = models.CASCADE,related_name='grade_cby')

    class Meta:
        ordering = ['-id']
        verbose_name = '班级'
        verbose_name_plural = verbose_name
    
    def __str__(self):
        # 返回班级名称
        return self.name

@admin.register(Grade)
class GradeAdminModel(admin.ModelAdmin):
    # 添加分页
    list_per_page = 20
    list_display = ('name','createdBy',)
    # 搜索框
    search_fields = ('name','createdBy__name')

# 课程
class Course(models.Model):
    """ 课程模型 """

    name = models.CharField(max_length=20, verbose_name='课程名称', help_text='课程名称（CharField）')
    courseType = models.CharField(max_length=20, verbose_name='课程类型', help_text='课程类型（CharField）', blank=True)
    desc = models.TextField(verbose_name='课程描述',help_text='课程描述（TextField）', blank=True)
    schoolTime = models.DateTimeField(verbose_name='上课时间', help_text='上课时间（DateTimeField）', null=True, blank=True)
    finishTime = models.DateTimeField(verbose_name='下课时间', help_text='下课时间（DateTimeField）', null=True, blank=True)
    createdBy = models.ForeignKey(UserExtension,max_length=20, verbose_name='创建人', help_text='创建人（CharField）', blank=True,on_delete = models.CASCADE,related_name='course_cby')
 
    class Meta:
        ordering = ['-id']
        verbose_name = '课程'
        verbose_name_plural = verbose_name

    def __str__(self):
        # 返回课程名称
        return self.name

@admin.register(Course)
class CourseAdminModel(admin.ModelAdmin):
    """
    注册课程模型到admin
    """
    list_per_page = 20
    list_display = ('id','name', 'courseType', 'desc', 'createdBy')
    search_fields = ('name','courseType', 'desc','createdBy__name')
    autocomplete_fields = ('createdBy',)

# 作业
class Homework(models.Model):
    """ 作业模型 """

    name = models.CharField(max_length=20, verbose_name='作业名称', help_text='作业名称（CharField）')
    courseType = models.CharField(max_length=20, verbose_name='作业类型', help_text='作业类型（CharField）', blank=True)
    desc = models.TextField(verbose_name='作业描述',help_text='作业描述（TextField）', blank=True)
    student = models.ForeignKey(UserExtension, verbose_name='学生', help_text='学生（ForeignKey）', null=True, blank=True, on_delete=models.SET_NULL)
    createdBy = models.ForeignKey(UserExtension, verbose_name='创建人', help_text='创建人（ForeignKey）',null=True, blank=True, on_delete=models.CASCADE, related_name='teacher')
    createdDate = models.DateTimeField(verbose_name='创建时间', help_text='创建时间（DateTimeField）', null=True, blank=True, auto_now_add=True)
    
    class Meta:
        ordering = ['-id']
        verbose_name = '作业'
        verbose_name_plural = verbose_name

    def __str__(self):
        # 返回作业名称
        return self.name

@admin.register(Homework)
class HomeworkAdminModel(admin.ModelAdmin):
    """
    注册作业模型到admin
    """
    list_per_page = 20
    list_display = ('id','name', 'courseType'
    , 'desc', 'createdBy', 'createdDate','student', )
    search_fields = ('name','courseType', 'desc'
    , 'createdBy__name', 'createdDate','student__name')
    list_filter = ('createdDate',)
    autocomplete_fields = ('student','createdBy',)
    

# 作业完成结果记录表
class HomeworkCheckTask(models.Model):
    """
    作业完成结果记录表
    """
    result_choices = (
        ('pass', '合格'),
        ('fail', '不合格'),
    )
    
    homework = models.OneToOneField(Homework, verbose_name='作业',help_text='作业（OneToOneField）', null=True, blank=True, on_delete=models.CASCADE)
    result = models.CharField(max_length=30, null=True, blank=True, verbose_name='作业结果', choices=result_choices,help_text='作业结果（CharField），可选项为：合格（pass）、不合格（fail）')
    runner = models.ForeignKey(UserExtension, verbose_name='学生', help_text='学生（ForeignKey）',null=True, blank=True, on_delete=models.SET_NULL, related_name='homeworkchecktask_rnr')
    runStartTime = models.DateTimeField(verbose_name='作业开始时间', help_text='作业开始时间（DateTimeField）', null=True, blank=True)
    runEndTime = models.DateTimeField(verbose_name='作业结束时间', help_text='作业结束时间（DateTimeField）', null=True, blank=True)

    class Meta:
        ordering = ['-id']
        verbose_name = '作业执行结果'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.homework.name

@admin.register(HomeworkCheckTask)
class HomeworkCheckTaskAdminModel(admin.ModelAdmin):
    """
    注册作业完成结果记录表到admin
    """
    # 添加分页
    list_per_page = 20
    # 列表页展示的字段
    list_display = ('homework','runner','runStartTime','runEndTime','result')
    # 提供引用查询
    search_fields = ('homework','runner__name')
    list_filter = ('result','runStartTime','runEndTime')
    autocomplete_fields = ('runner',)


# 用户肖像图片
class UserPortrait(models.Model):
    """ 用户肖像图片 """

    user = models.ForeignKey(UserExtension ,verbose_name='用户id', help_text='用户id（ForeignKey）', null=True,  blank=True,on_delete=models.SET_NULL,related_name='userportrait')
    portrait = models.ForeignKey('Portrait' ,verbose_name='图片id', help_text='图片id（ForeignKey）', null=True,  blank=True,on_delete=models.SET_NULL) 
    createdBy = models.ForeignKey(UserExtension,max_length=30, verbose_name='创建者', help_text='创建者（ForeignKey）', blank=True,on_delete = models.CASCADE,related_name='userportrait_cby')
    createdDate = models.DateTimeField(verbose_name='创建时间', help_text='创建时间（DateTimeField）', null=True, blank=True, auto_now_add=True)
    lastEditedBy = models.ForeignKey(UserExtension,max_length=30, verbose_name='最后编辑人', help_text='最后编辑人（CharField', blank=True,on_delete = models.CASCADE,related_name='userportrait_eby')
    lastEditedDate = models.DateTimeField(verbose_name='最后编辑时间', help_text='最后编辑时间（DateTimeField）', null=True, blank=True, auto_now=True)

    class Meta:
        ordering = ['-id']
        verbose_name = '用户肖像图片'
        verbose_name_plural = verbose_name

    def __str__(self):
        return str(self.portrait.portrait) + '-' + str(self.user.name)

@admin.register(UserPortrait)
class UserPortraitAdminModel(admin.ModelAdmin):
    list_display = ('user','portrait', 'createdBy'
    , 'lastEditedBy','createdDate', 'lastEditedDate')
    list_per_page = 20
    search_fields = ('user__name','portrait__portrait'
    , 'createdBy__name','lastEditedBy__name')
    list_filter = ('createdDate','lastEditedDate')
    autocomplete_fields = ('user','createdBy','lastEditedBy')
    
# 肖像图片
class Portrait(models.Model):
    """ 肖像图片 """

    portrait =models.ImageField(upload_to='img/user/portrait', verbose_name='头像', help_text='头像（ImageField）', blank=True,default='img/user/portrait/default_portrait.jpg')
    createdBy = models.ForeignKey(UserExtension,max_length=30, verbose_name='创建者', help_text='创建者（ForeignKey）', blank=True,on_delete = models.CASCADE,related_name='portrait_cby')
    createdDate = models.DateTimeField(verbose_name='创建时间', help_text='创建时间（DateTimeField）', null=True, blank=True, auto_now_add=True)
    lastEditedBy = models.ForeignKey(UserExtension,max_length=30, verbose_name='最后编辑人', help_text='最后编辑人（ForeignKey', blank=True,on_delete = models.CASCADE,related_name='portrait_eby')
    lastEditedDate = models.DateTimeField(verbose_name='最后编辑时间', help_text='最后编辑时间（DateTimeField）', null=True, blank=True, auto_now=True)

    class Meta:
        ordering = ['-id']
        verbose_name = '肖像图片'
        verbose_name_plural = verbose_name

    def __str__(self):
        return str(self.portrait)

@admin.register(Portrait)
class PortraitAdminModel(admin.ModelAdmin):
    list_display = ('portrait', 'createdBy', 'createdDate'
    , 'lastEditedBy', 'lastEditedDate')
    list_per_page = 20
    

# 课堂图片
class Images(models.Model):
    """ 课堂图片 """
    now = str(now().strftime('%Y_%m'))

    images = models.ImageField(upload_to='img/student/images/%Y/%m/', verbose_name='学生课堂图片', help_text='学生课堂图片（ImageField）', null=True, blank=True)
    title = models.CharField(max_length=255, verbose_name='文件名称', help_text='文件名称', blank=True)
    createdBy = models.ForeignKey(UserExtension,max_length=30, verbose_name='创建者', help_text='创建者（CharField）', blank=True,on_delete = models.CASCADE,related_name='images_cby')
    createdDate = models.DateTimeField(verbose_name='创建时间', help_text='创建时间（DateTimeField）',auto_now_add=True, null=True, blank=True)
    lastEditedBy = models.ForeignKey(UserExtension,max_length=30, verbose_name='最后编辑人', help_text='最后编辑人（CharField', blank=True,on_delete = models.CASCADE,related_name='images_eby')
    lastEditedDate = models.DateTimeField(verbose_name='最后编辑时间', help_text='最后编辑时间（DateTimeField）', auto_now=True, null=True, blank=True)

    class Meta:
        ordering = ['-id']
        verbose_name = '课堂图片'
        verbose_name_plural = verbose_name
    
    def __str__(self):
        return self.title

@admin.register(Images)
class ImagesAdminModel(admin.ModelAdmin):
    list_per_page = 20
    list_display = ('id','images', 'title','createdBy'
    , 'lastEditedBy','createdDate', 'lastEditedDate')
    search_fields = ('title','createdBy__name', 'createdDate'
    ,'lastEditedBy__name', 'lastEditedDate')
    list_filter = ('createdDate','lastEditedDate')
    autocomplete_fields = ('createdBy','lastEditedBy')

# 用户学习图片
class UserImage(models.Model):
    """ 用户学习图片 """

    user = models.ForeignKey(UserExtension ,verbose_name='id', help_text='用户id（ForeignKey）', null=True,  blank=True,on_delete=models.SET_NULL,related_name='userimage')
    image = models.ForeignKey(Images ,verbose_name='图片id', help_text='图片id（ForeignKey）', null=True,  blank=True,on_delete=models.SET_NULL) 
    createdBy = models.ForeignKey(UserExtension,max_length=30, verbose_name='创建者', help_text='创建者（ForeignKey）', blank=True,on_delete = models.CASCADE,related_name='userimage_cby')
    createdDate = models.DateTimeField(verbose_name='创建时间', help_text='创建时间（DateTimeField）', null=True, blank=True, auto_now_add=True)
    lastEditedBy = models.ForeignKey(UserExtension,max_length=30, verbose_name='最后编辑人', help_text='最后编辑人（CharField', blank=True,on_delete = models.CASCADE,related_name='userimage_eby')
    lastEditedDate = models.DateTimeField(verbose_name='最后编辑时间', help_text='最后编辑时间（DateTimeField）', null=True, blank=True, auto_now=True)

    class Meta:
        ordering = ['-id']
        verbose_name = '用户学习图片'
        verbose_name_plural = verbose_name

    def __str__(self):
        return str(self.image.images) + '-' + str(self.user.name)

@admin.register(UserImage)
class UserImageAdminModel(admin.ModelAdmin):
    list_display = ('user','image', 'createdBy'
    , 'lastEditedBy','createdDate', 'lastEditedDate')
    list_per_page = 20
    search_fields = ('user__name','image__images'
    , 'createdBy__name','lastEditedBy__name')
    list_filter = ('createdDate','lastEditedDate')
    autocomplete_fields = ('user','createdBy','lastEditedBy')


# 文件存储
class Files(models.Model):
    """ 文件存储，主要是存视频 """
    now = str(now().strftime('%Y_%m'))
    type_choices = (('mp4', 'mp4视频'),('mkv', 'mkv视频'),('apk', '安装包'),('pdf', 'pdf文档'))

    title = models.CharField(max_length=255, verbose_name='文件名称', help_text='文件名称', blank=True)
    fileType = models.CharField(max_length=30,verbose_name='所属类型',help_text='类型（所属类型CharField，可选值：mp4，mkv，apk，pdf）', choices=type_choices, default='problem')
    fileUrl = models.FileField(upload_to='file/%Y/%m/', verbose_name='文件路径', help_text='文件路径（FileField）', null=True, blank=True)
    createdBy = models.ForeignKey(UserExtension,max_length=30, verbose_name='创建者', help_text='创建者（CharField）', blank=True,on_delete = models.CASCADE,related_name='files_cby')
    createdDate = models.DateTimeField(verbose_name='创建时间', help_text='创建时间（DateTimeField）', auto_now_add=True,null=True, blank=True)
    lastEditedBy = models.ForeignKey(UserExtension,max_length=30, verbose_name='最后编辑人', help_text='最后编辑人（CharField', blank=True,on_delete = models.CASCADE,related_name='files_eby')
    lastEditedDate = models.DateTimeField(verbose_name='最后编辑时间', help_text='最后编辑时间（DateTimeField）', auto_now=True,null=True, blank=True)

    class Meta:
        ordering = ['-id']
        verbose_name = '文件存储'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.title


@admin.register(Files)
class FilesAdminModel(admin.ModelAdmin):
    """
    注册文件存储模型到admin
    Author: czj
    """
    list_per_page = 20
    list_display = ('id','title', 'fileType', 'fileUrl'
    , 'createdBy',  'lastEditedBy'
    , 'createdDate','lastEditedDate')
    search_fields = ('title', 'fileType', 'fileUrl'
    , 'createdBy__name', 'lastEditedBy__name','createdDate', 'lastEditedDate')
    list_filter = ('createdDate','lastEditedDate')
    autocomplete_fields = ('createdBy','lastEditedBy')

# 用户学习文件存储
class UserFile(models.Model):
    """ 用户学习文件存储 """

    user = models.ForeignKey(UserExtension ,verbose_name='id', help_text='用户id（ForeignKey）', null=True,  blank=True,on_delete=models.SET_NULL,related_name='userfile')
    file = models.ForeignKey(Files ,verbose_name='文件id', help_text='文件id（ForeignKey）', null=True,  blank=True,on_delete=models.SET_NULL) 
    createdBy = models.ForeignKey(UserExtension,max_length=30, verbose_name='创建者', help_text='创建者（ForeignKey）', blank=True,on_delete = models.CASCADE,related_name='userfile_cby')
    createdDate = models.DateTimeField(verbose_name='创建时间', help_text='创建时间（DateTimeField）', null=True, blank=True, auto_now_add=True)
    lastEditedBy = models.ForeignKey(UserExtension,max_length=30, verbose_name='最后编辑人', help_text='最后编辑人（CharField', blank=True,on_delete = models.CASCADE,related_name='userfile_eby')
    lastEditedDate = models.DateTimeField(verbose_name='最后编辑时间', help_text='最后编辑时间（DateTimeField）', null=True, blank=True, auto_now=True)

    class Meta:
        ordering = ['-id']
        verbose_name = '用户学习文件存储'
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.file.title + '-' + self.user.name

@admin.register(UserFile)
class UserFileAdminModel(admin.ModelAdmin):
    list_display = ('user','file', 'createdBy'
    ,'lastEditedBy','createdDate','lastEditedDate')
    list_per_page = 20
    search_fields = ('user__name','file__files'
    , 'createdBy__name','lastEditedBy__name')
    list_filter = ('createdDate','lastEditedDate')
    autocomplete_fields = ('user','createdBy','lastEditedBy')

@receiver(post_save, sender=User)
def create_user_extension(sender, instance, created, **kwargs):
    if created:
        userobj = UserExtension.objects.create(user=instance)
        if instance.last_name + instance.first_name != '':
            userobj.name = instance.last_name + instance.first_name
            userobj.save()
    else:
        # userobj = UserExtension.objects.get_or_create(user=instance)
        userobj = UserExtension.objects.filter(user=instance).first()
        if userobj:
            if instance.last_name + instance.first_name != '':
                userobj.name = instance.last_name + instance.first_name
                userobj.save()
        else:
            userobj = UserExtension.objects.create(user=instance)
            if instance.last_name + instance.first_name != '':
                userobj.name = instance.last_name + instance.first_name
                userobj.save()
